﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;
using YeqianFramework.core;

namespace YeqianFramework.common
{
	//[RequireComponent(typeof(Text))]
	public class UIDebugeField : MonoBehaviourSingleton<UIDebugeField>
	{
		private bool isContentUpdate = false;
		public bool isActive;
		public Dictionary<string, StringBuilder> Content { get; private set; }
		/// <summary>
		/// 显示key的字号
		/// </summary>
		public int keySize = 25;
		/// <summary>
		/// 显示正文的字号
		/// </summary>
		public int contentSize = 18;

		protected override void Awake()
		{
			base.Awake();

			//m_text = GetComponent<Text>();
			isActive = true;
		}

		protected override void Init()
		{
			Content = new Dictionary<string, StringBuilder>();
		}

		[TextArea(5,30)]
		public string txt;
		private StringBuilder builder = new StringBuilder();
		public string GetFieldText()
		{
			if (isContentUpdate)
			{
				builder.Clear();
				foreach (var item in Content)
				{
					builder.AppendLine(string.Format("<color=#ffffff><b><size={0}>{1}</size></b></color>", keySize, item.Key));
					builder.AppendLine(string.Format("<color=#ffffff><size={0}>{1}</size></color>", keySize, item.Value));
					//builder.AppendLine(item.Key);
					//builder.AppendLine(item.Value.ToString());
				}
				isContentUpdate = false;
			}

			txt = builder.ToString();
			return builder.ToString();
		}

		private string inputVal = string.Empty;
		private void OnGUI()
		{
			if (!isActive) return;
			Rect rect = new Rect(10, 10, Screen.width - 20, Screen.height - 55);
			GUILayout.BeginArea(rect);

			GUIStyle gUIStyle = new GUIStyle();
			gUIStyle.richText = true;

			GUILayout.Label(GetFieldText());
			GUILayout.EndArea();

			GUILayout.BeginArea(new Rect(10, Screen.height - 35, Screen.width - 20, 25));
			inputVal = GUILayout.TextField(inputVal);
			GUILayout.EndArea();
		}

		/// <summary>
		/// 新建Debug信息
		/// </summary>
		public void AddMessage(string key, string msg)
		{
			if (!Content.ContainsKey(key))
			{
				Content.Add(key, new StringBuilder());
			}

			Content[key].AppendLine(msg);
			isContentUpdate = true;
		}

		/// <summary>
		/// 修改消息
		/// </summary>
		/// <param name="key"></param>
		/// <param name="msg"></param>
		public void UpdateMessage(string key, string msg)
		{
			if (!Content.ContainsKey(key))
			{
				Content.Add(key, new StringBuilder());
			}
			Content[key].Clear();
			Content[key].AppendLine(msg);

			isContentUpdate = true;
		}

		/// <summary>
		/// 移除Debug信息
		/// </summary>
		/// <param name="key"></param>
		public void RemoveMessage(string key)
		{
			if (!Content.ContainsKey(key))
			{
				throw new KeyNotFoundException("未找到消息名：" + key);
			}

			Content.Remove(key);

			isContentUpdate = true;
		}

	}
}
